package com.eascs.web.captcha.controller;

import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.web.captcha.patchca.service.Captcha;
import com.eascs.web.context.ResponseContext;

@Controller
public class CaptchaController {

	private static final Logger LOGGER = LoggerFactory.getLogger(CaptchaController.class);

	private CaptchaBuilder captchaBuilder = new CaptchaBuilder();

	@RequestMapping(value = "/captcha/yzm.png")
	public void buidCaptchaImage(HttpServletResponse resp) throws IOException {
		ResponseContext.setContentType(MediaType.IMAGE_PNG_VALUE);
		ResponseContext.setDateHeader("Expries", 0);
		ResponseContext.setHeader("Pragma", "no-cache");
		Captcha captcha = captchaBuilder.buildCaptcha();
		CaptchaBuilder.SESSION_CAPTCHA.setValue(captcha.getChallenge());
		try {
			ImageIO.write(captcha.getImage(), "png", ResponseContext.getOutputStream());
		} catch (IOException e) {

		}
	}

	@ExceptionHandler
	@ResponseBody
	public String exception(Exception exception) {
		LOGGER.error(exception.getMessage(), exception);
		return "请求失败";
	}

}
